<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>JS模块化</title>
</head>
<body>
	<script type="text/javascript">
		// 当我们加载多个 js 文件时，最终还是会在一个全局作用域下，这时候变量提升、变量命名可能会导致多个文件公用一个变量名称，对变量进行操作修改时，容易引起其他文件的冲突
		function array2Tree(arr){
		    if(!Array.isArray(arr) || !arr.length) return;
		    let map = {};
		    arr.forEach(item => map[item.id] = item);

		    let roots = [];
		    arr.forEach(item => {
		        const parent = map[item.parentId];
		        if(parent.parentId !== item.id){
		            (parent.children || (parent.children=[])).push(item);
		        }
		        else{
		            roots.push(item);
		        }
		    })

		    return roots;
		}
		const arr = [
		    {id:1, parentId: 1, name: 'a'},
		    {id:2, parentId: 2, name: 'b'},
		    {id:3, parentId: 1, name: 'c'},
		    {id:4, parentId: 2, name: 'd'},
		    {id:5, parentId: 1, name: 'e'},
		    {id:6, parentId: 3, name: 'f'},
		    {id:7, parentId: 4, name: 'g'},
		    {id:8, parentId: 7, name: 'h'},
		]
		const arr1 = array2Tree(arr)
		console.log(arr1)
	</script>
</body>
</html>